import * as types from './action-types'
import { httpUrl, ERR_OK } from 'api/config'
import { ajaxGet } from 'api/axios'
import { successNotify, errorNotify } from 'common/js/dom'
import { setUserIng } from 'common/js/util'
import { actionCreators as appActionCreators } from 'src/store/app'

const changeLoading = (bol) => ({
  type: types['CHANGE_LOADING'],
  bol
})

export const setCodeTextAction = (value) => ({
  type: types['SET_CODE_TEXT'],
  value
})

export const goLoginAction = ({ userName, password }, history) => {
  return (dispatch) => {
    dispatch(changeLoading(true))

    const url = `${httpUrl}/sys_login`

    ajaxGet(url, {
      userName,
      password
    }).then(res => {
      if (res.code === ERR_OK) {
        const result = res.data
        setUserIng(result)
        dispatch(appActionCreators.changeUserInfoAction(result))
        successNotify({
          message: 'Login success',
          description: '登录成功',
          duration: 0.7
        })
        setTimeout(() => {
          history.replace('/home')
        }, 800)
      } else {
        errorNotify({
          message: 'Login Fail',
          description: res.msg
        })
      }
      dispatch(changeLoading(false))
    })
  }
}
